package com.example.im.mvp.presenter

import android.app.ProgressDialog
import android.content.Context
import com.example.im.xmpp.IMConnection
import com.example.im.common.Constants
import com.example.im.entity.InviteCode
import com.example.im.http.APIRetrofit
import com.example.im.http.RetrofitManager
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IAccessView
import com.example.im.utils.ACache
import com.example.im.utils.RandomUntil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers

class AccessPresenter(mContext: Context, mView: IAccessView?) :
    BasePresenter<IAccessView>(mContext, mView) {

    private var dialog: ProgressDialog? = null

    init {
        dialog = ProgressDialog(mContext)
        dialog!!.setCanceledOnTouchOutside(false)
        dialog!!.setMessage("请稍候...")
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    fun userSignIn(userName: String, userPwd: String) {

        if (userName.isEmpty()) {
            getView().onHint("请输入用户名")
            return
        }
        if (userPwd.isEmpty()) {
            getView().onHint("请输入用户密码")
            return
        }

        val disposables: Disposable = Observable.combineLatest(
            Observable.just(userName),
            Observable.just(userPwd),
            BiFunction<String, String, Boolean> { t1, t2 ->
                IMConnection.instance!!.login(t1, t2)
            }
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    val preferences = getContext()
                        .getSharedPreferences(Constants.ACCOUNT_ATTRIBUTES, Context.MODE_PRIVATE)
                    val editor = preferences.edit()
                    editor.putString(Constants.ACCOUNT_USER_NAME, userName)
                    editor.putString(Constants.ACCOUNT_PASSWORDS, userPwd)
                    editor.apply()
                    getView().onLoginSuccess()
                },
                { error ->
                    getView().onHint(error.message!!)
                    dialog!!.cancel()
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )

        this.disposable.add(disposables)
    }

    fun userSignUp(name: String, userPwd: String, code: String) {

        if (name.isEmpty()) {
            getView().onHint("请输入昵称")
            return
        }
        if (userPwd.isEmpty()) {
            getView().onHint("请输入密码")
            return
        }
        if (userPwd.length < 6) {
            getView().onHint("用户密码不能少于6位数")
            return
        }
        if (code.isEmpty()) {
            getView().onHint("请输入邀请码")
            return
        }

        val disposables: Disposable = Observable.just(mutableMapOf("inviteCode" to code))
            .subscribeOn(Schedulers.io())
            .flatMap {
                RetrofitManager.retrofit().create(APIRetrofit::class.java)
                    .getInviteCode(it)
                    .onErrorReturn {
                        with(InviteCode(), {
                            this.code = -1
                            this.data = null
                            this
                        })
                    }
            }
            .map {
                if (it.code != 0 || it.data == null) {
                    false
                } else {
                    val aCache = ACache.get(getContext())
                    aCache.put("INVITE_CODE",it.data.toString())
                    IMConnection.instance!!.userSearch(it.data.toString()).isEmpty()
                }
            }
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                if (!it) {
                    getView().onHint("注册失败，验证码错误！")
                }
                return@filter it
            }
            .subscribeOn(Schedulers.io())
            .map {
                val account = RandomUntil.getNumLetter(9)
                if (IMConnection.instance!!.logon(account, name, userPwd))
                    account else ""
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it.isEmpty())
                        getView().onHint("注册失败")
                    else
                        getView().onLogonSuccess(it)
                },
                { error ->
                    getView().onHint(error.message!!)
                    dialog!!.cancel()
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(disposables)
    }
}